﻿using System;
using System.Collections.Generic;
using System.Management;
using static System.Management.ManagementObjectCollection;

namespace LeanApp.Common
{
    /// <summary>
    /// 硬件工具
    /// </summary>
    public class HardwareTool
    {
        /// <summary>
        /// 用户密钥
        /// </summary>
        public static readonly string _userKey = "EASY.COM";
        /// <summary>  
        /// 获取CpuId  
        /// </summary>  
        /// <returns>CpuId</returns>  
        public static string GetCpuId()
        {
            try
            {
                ManagementClass val = new ManagementClass("Win32_Processor");
                ManagementObjectCollection instances = val.GetInstances();
                List<string> cpuList = new List<string>();
                ManagementObjectEnumerator enumerator = instances.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        ManagementBaseObject current = enumerator.Current;
                        cpuList.Add(current["Processorid"].ToString());
                    }
                }
                finally
                {
                    ((IDisposable)enumerator)?.Dispose();
                }
                return string.Join(",", cpuList.ToArray());
            }
            catch
            {
                return "unknown";
            }
        }

        /// <summary>  
        /// 获取本机MAC地址  
        /// </summary>  
        /// <returns>本机MAC地址</returns>  
        public static string GetMacAddress()
        {
            try
            {
                ManagementClass val = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection instances = val.GetInstances();
                List<string> macList = new List<string>();
                ManagementObjectEnumerator enumerator = instances.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        ManagementBaseObject current = enumerator.Current;
                        if (current["IPEnabled"].ToString() == "True" && !current["Caption"].ToString().ToLower().Contains("virtual"))
                        {
                            macList.Add(current["MacAddress"].ToString().Replace(":", "-"));
                        }
                    }
                }
                finally
                {
                    ((IDisposable)enumerator)?.Dispose();
                }

                return string.Join(",", macList.ToArray());
            }
            catch
            {
                return "unknown";
            }
        }
    }
}
